import React, { Component } from 'react'
import  { Card, Table, message, Button,Modal }from 'antd'
import LinkButton from '../../components/link-button';
import {reqUserList,reqAddUser,reqDeleteUser,reqUpdateUser} from '../../api'
import {formatDate} from '../../utils/defaultDate.js'
import  AdduserForm from  './adduserForm.js'
export class User extends Component {
   state={
       userList:[],
       roles:[],
       addUserModal:false
   }


    initClumns=()=>{
      return  this.columns=[
            {
                title:'用户名',
                dataIndex:'username'
        },
        {
            title:'邮箱',
            dataIndex:'email'
        },    {
        title:'电话',
        dataIndex:'phone'
     }, 
       {
        title:'注册时间',
        dataIndex:'create_time',
        render: formatDate
     }, 
       {
        title:'所属角色',
        dataIndex:'role_id',
        render:(role_id)=>this.roleNames[role_id]
     
        },   
     {
      title:'操作',
      render:(user)=>(
       <span>
        <LinkButton onClick={()=>this.updateUser(user)}>修改</LinkButton>
        <LinkButton onClick={()=>this.deleteUser(user)}>删除</LinkButton>
         </span>
         )
        },
        
        ]
    }

    componentWillMount(){
        this.initClumns()
    }

    componentDidMount(){
        this.getUserDataList()
    }

    initRoleCloumns=(roles)=>{

        const roleNames = roles.reduce((pre, role) => {
            pre[role._id] = role.name
            return pre
          }, {})
          // 保存
          console.log('reduce===>',roleNames)
          this.roleNames = roleNames
    }

   getUserDataList= async ()=>{
       const userData =  await reqUserList();
       if(userData.status===0){
           const {roles,users} = userData.data
           this.initRoleCloumns(roles)
           this.setState({
               userList:users,
               roles,
           })
       }
   }

   addUserModal= async ()=>{
       this.setState({
           addUserModal:false
       })

    const users =   this.form.getFieldsValue();
 
    this.form.resetFields()
    if(this.user){
         users._id= this.user._id 
         const result = await reqUpdateUser(users)
         if(result.status === 0){
            this.getUserDataList()
         }
         else{
             message.error('更新用户失败')
         }
    }else{
        const result = await reqAddUser(users);
        if(result.status===0){
            this.getUserDataList()
        }else{
            message.error('此用户已经存在')
        }

    }
       
    
   }
   deleteUser=(user)=>{
    const userId = user._id
    console.log('user===>',user)
       Modal.confirm({
        title: `您确定删除${user.username}吗？`,
        
        okText: 'Yes',
        okType: 'danger',
        cancelText: 'No',
        onOk:async ()=> {
           const res = await reqDeleteUser(userId)
           if(res.status===0){
               message.success('删除成功');
               this.getUserDataList()
           }
        },
     
    
          });

     
   }
   updateUser=(user)=>{
       console.log('更修用户===》',user)

       this.setState({
           addUserModal:true
       })

       this.user = user
  

   }


    render() {
        const { userList,addUserModal,roles} = this.state
        const title = (
            <Button type='primary' onClick={()=>this.setState({addUserModal:true})}>创建角色</Button>
        )

        const user = this.user || {}
        return (
            <div>
               <Card title={title} >
                <Table
                  rowKey= "_id"
                  bordered
                 columns={this.columns}
                 dataSource={userList } 
                 pagination={{
                    defaultPageSize:3
                 }}
                 />
                 <Modal
                 title='添加角色'
                 visible={addUserModal}
                  onOk={this.addUserModal}
                  onCancel={()=>this.setState({addUserModal:false})}
                 >
                 <AdduserForm  
                 setForm={form=>this.form=form}
                 roles={roles}
                 
                   user={user}
                 />
                 
              
                 </Modal>


                </Card>
            </div>
        )
    }
}

export default User
